import 'package:bilibili/http/core/hi_error.dart';
import 'package:bilibili/http/dao/login_dao.dart';
import 'package:bilibili/navigator/hi_navigator.dart';
import 'package:bilibili/util/color.dart';
import 'package:bilibili/util/toast.dart';
import 'package:bilibili/widget/appbar.dart';
import 'package:bilibili/widget/login_button.dart';
import 'package:bilibili/widget/login_effect.dart';
import 'package:bilibili/widget/login_input.dart';
import 'package:flutter/material.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<StatefulWidget> createState() {
    return _LoginEffectState();
  }
}

class _LoginEffectState extends State<LoginPage> {
  bool isProtect = false;
  String username = "";
  String password = "";
  bool loginEnable = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: appBar("密码登录", "注册", () {
        HiNavigator.getInstance().onJumpTo(RouteStatus.registration);
      }),
      body: ListView(
        children: [
          LoginEffect(protect: isProtect),
          LoginInput(
            "用户名",
            "请输入用户名",
            linStretch: true,
            onChanged: (value) {
              username = value;
              _chechParams();
            },
          ),
          LoginInput(
            "密码",
            "请输入密码",
            linStretch: true,
            obscureText: true,
            onChanged: (value) {
              password = value;
              _chechParams();
            },
            foucusChanged: (value) => {
              setState(() {
                isProtect = value;
              })
            },
          ),
          Padding(
              padding: EdgeInsets.all(20),
              // child: _loginButton(),
              child: LoginButton(
                '登录',
                enable: loginEnable,
                onClicked: send,
              ))
        ],
      ),
    );
  }

  Widget _loginButton() {
    return InkWell(
      onTap: () {},
      child: Container(
        height: 42,
        alignment: Alignment.center,
        decoration: BoxDecoration(
            color: loginEnable ? primary : primary[50],
            borderRadius: BorderRadius.circular(4)),
        child: Text(
          "登录",
          style: TextStyle(fontSize: 16, color: white),
        ),
      ),
    );
  }

  _chechParams() {
    bool enable = false;
    if (username.isNotEmpty && password.isNotEmpty) {
      enable = true;
    }

    setState(() {
      loginEnable = enable;
    });
  }

  send() async {
    try {
      var ret = LoginDao.login(username, password);
      print(ret);
      showToast("登陆成功");

      HiNavigator.getInstance().onJumpTo(RouteStatus.home);
    } on NeedAuth catch (e) {
      print(e);
      showWarningToast(e.message);
    } on HiNetError catch (e) {
      print(e);
      showWarningToast(e.message);
    }
  }
}
